package com.briup.pts.service.impl;

import com.briup.pts.config.exception.ServiceException;
import com.briup.pts.config.response.ResultCode;
import com.briup.pts.domain.bean.FenceHouse;
import com.briup.pts.domain.vo.FenceHouseVO;
import com.briup.pts.mapper.FenceHouseMapper;
import com.briup.pts.service.FenceHouseService;
import com.briup.pts.utils.UuidUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
@RequiredArgsConstructor
public class FenceHouseServiceImpl implements FenceHouseService {

    private final FenceHouseMapper mapper;

    @Override
    public PageInfo<FenceHouse> pageQuery(Integer pageNum, Integer pageSize,
                                          String fhName) {
        // 使用PageHelper插件开启分页，进行查询
        try (Page<FenceHouse> ignored = PageHelper.startPage(pageNum, pageSize)) {
            // 进行条件查询
            List<FenceHouse> houseList = mapper.queryByConditional(fhName);
            Page<FenceHouse> page = (Page<FenceHouse>) houseList;
            return new PageInfo<>(page);
        }
    }

    @Override
    public FenceHouseVO queryById(String fhId) {
        return mapper.queryById(fhId);
    }

    @Override
    public void saveOrUpdate(FenceHouse fenceHouse) {
        // 根据传入的参数判定是新增还是修改
        if (StringUtils.hasText(fenceHouse.getFhId())) {
            // 传入了对应的id，那么表明需要修改操作
            mapper.updateFH(fenceHouse);
        } else {
            // 没有传入id，说明需要新增，注意新增的栏舍id需要我们自定义
            // 使用UUID生成对应的栏舍id
            fenceHouse.setFhId(UuidUtil.generator());
            // 进行新增操作
            mapper.insertFH(fenceHouse);
        }
    }

    @Override
    public void deleteBatch(List<String> fhIds) {
        if (CollectionUtils.isEmpty(fhIds)) {
            throw new ServiceException(ResultCode.PARAMS_IS_INVALID);
        }
        // 直接删除
        mapper.deleteBatch(fhIds);
    }
}
